package com.example.lenovo.asia5b.home.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.lenovo.asia5b.home.activity.HolidayDialogActivity;
import com.example.lenovo.asia5b.home.activity.LoginActivity;
import com.example.lenovo.asia5b.home.adapter.MianShopingCartAdapter;
import com.example.lenovo.asia5b.home.bean.BdShippingBean;
import com.example.lenovo.asia5b.home.bean.ShippingBean;
import com.example.lenovo.asia5b.home.bean.ShopingCartBean;
import com.example.lenovo.asia5b.my.activity.AddressActivity;
import com.example.lenovo.asia5b.my.activity.MessageActivity;
import com.example.lenovo.asia5b.my.bean.AddressBean;
import com.example.lenovo.asia5b.my.bean.ShippingPersonBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout;
import com.example.lenovo.asia5b.util.CommonUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.example.lenovo.asia5b.util.keyboardUtil;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseFragment;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.home.fragment.MianHomeFragment.message_count;
import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;


/**
 * 购物车
 * Created by lenovo on 2017/6/20.
 */

public class MianShopingCartFragment extends BaseFragment implements ICallBack,PullToRefreshLayout.OnRefreshListener{
    private View fragmentView;
    private ListView lv_shoping_cart;
    private MianShopingCartAdapter adapter;
    public List<ShopingCartBean> lists = new ArrayList<ShopingCartBean>();
    private PullToRefreshLayout pullToRefreshLayout;
    //全选
    private CheckBox cb_check_all;
    private TextView txt_total_price,txt_address,txt_hint;
    private Button btn_settlement;
    private double totalPrice = 0;
    private TextView txt_edit;
    public boolean isVisibilityTit  = false;
    private LoadingDalog loadingDalog;
    private View header;
    private View botton;
    private LayoutInflater inflater;
    private TextView txt_consignee,txt_addres,txt_mobile;
    private Spinner spr_shipping,spr_transport;
    //收货地址ID，收货人ID,国际运输ID，本地运输ID
    private String  address_id,contact_id,shipping_id,transport_id;

    //地址
    private LinearLayout frame_order_address;

    private RelativeLayout rl_mess;
    private static  TextView txt_mess,txt_email;
    private static  RelativeLayout rl_shape;
    private LinearLayout ll_email;
    //设个默认值先
    private String shipping_type="3492";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.frame_main_shoping_cart, container,
                false);

        initView();
        ressListData();
        personListData();
        bdShippingData();
        receiveAdDownload();
        return fragmentView;
    }

    @Override
    public void onResume() {
        super.onResume();
//        cb_check_all.setChecked(false);
    }

    public void initView() {
        loadingDalog = new LoadingDalog(getActivity());
        loadingDalog.show();
        lv_shoping_cart = (ListView)fragmentView.findViewById(R.id.lv_shoping_cart);
        cb_check_all = (CheckBox) fragmentView.findViewById(R.id.cb_check_all);
        txt_total_price = (TextView) fragmentView.findViewById(R.id.txt_total_price);
        btn_settlement  = (Button) fragmentView.findViewById(R.id.btn_settlement);
        txt_hint= (TextView)fragmentView.findViewById(R.id.txt_hint);
        pullToRefreshLayout = ((PullToRefreshLayout)fragmentView.findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(this);
        inflater = LayoutInflater.from(getActivity());
        header = (View)inflater.inflate(R.layout.frame_confirm_order_header_2,null);
        frame_order_address = (LinearLayout)header.findViewById(R.id.frame_order_address);
        frame_order_address.setOnClickListener(this);
        ll_email = (LinearLayout)header.findViewById(R.id.ll_email);
        txt_email = (TextView)header.findViewById(R.id.txt_email);
        txt_consignee = (TextView)header.findViewById(R.id.txt_consignee);
        txt_address = (TextView)header.findViewById(R.id.txt_address);
        txt_mobile = (TextView)header.findViewById(R.id.txt_mobile);
        spr_shipping = (Spinner) header.findViewById(R.id.spr_shipping);
        spr_transport = (Spinner) header.findViewById(R.id.spr_transport);
        lv_shoping_cart.addHeaderView(header);

        btn_settlement.setOnClickListener(this);
        txt_edit = (TextView)fragmentView.findViewById(R.id.txt_edit);
        adapter = new MianShopingCartAdapter(getActivity(),MianShopingCartFragment.this);
        adapter.setListBeans(lists);
        lv_shoping_cart.setAdapter(adapter);
        cb_check_all.setOnClickListener(this);
        txt_edit.setOnClickListener(this);
        //消息提示
        rl_mess = fragmentView.findViewById(R.id.rl_mess);
        rl_mess.setOnClickListener(this);
        txt_mess = (TextView)fragmentView.findViewById(R.id.txt_mess);
        rl_shape = fragmentView.findViewById(R.id.rl_shape);
    }

    /**
     * 消息数量
     */
    @Override
    public void onStart() {
        super.onStart();
        if (MianHomeFragment.message_count == 0) {
            rl_shape.setVisibility(View.GONE);
        } else {
            rl_shape.setVisibility(View.VISIBLE);
        }
        txt_mess.setText(""+MianHomeFragment.message_count);
    }

    public static  void setMessCount(int id) {
        if (null != txt_mess) {
            txt_mess.setText(""+MianHomeFragment.message_count);
            if (id == 0){
                rl_shape.setVisibility(View.GONE);
            } else {
                rl_shape.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.cb_check_all:
                totalPrice = 0;
                if (cb_check_all.isChecked()) {
                    for (int i= 0;  i < adapter.getListBeans().size();i++) {
                        ShopingCartBean bean = adapter.getListBeans().get(i);
                        bean.isSelected = true;
                        double price = Double.parseDouble(bean.goods_price);
                        int num = Integer.parseInt(bean.goods_number);
                        totalPrice = totalPrice + price* num;
                    }
                } else {
                    for (int i= 0;  i < adapter.getListBeans().size();i++) {
                        adapter.getListBeans().get(i).isSelected = false;
                    }
                }
                adapter.notifyDataSetChanged();
                txt_total_price.setText("RM "+bigDecimal(totalPrice));
                settlementSum();
                break;
            case R.id.txt_edit:
                if (isVisibilityTit) {
                    alterNumber();
                    isVisibilityTit = false;
                    txt_edit.setText(getResources().getString(R.string.edit));
                    keyboardUtil.HideKeyboard(txt_edit);
                } else {
                    isVisibilityTit = true;
                    txt_edit.setText(getResources().getString(R.string.complete));
                }
                for (int i= 0;  i < adapter.getListBeans().size();i++) {
                    ShopingCartBean bean = adapter.getListBeans().get(i);
                    bean.isState = isVisibilityTit;
                }
                adapter.isVisibilityTit = isVisibilityTit;
                adapter.notifyDataSetChanged();
                break;
            case R.id.btn_settlement:
                settlementData();
                break;
            case R.id.frame_order_address:
                startActivityForResult(new Intent(getActivity(),AddressActivity.class),0);
                break;
            case R.id.rl_mess:
                if(null == getUserBean()) {
                    intent = new Intent(getActivity(), LoginActivity.class);
                } else {
                    intent = new Intent(getActivity(), MessageActivity.class);
                    rl_shape.setVisibility(View.GONE);
                    MianHomeFragment.message_count = 0;
                    SharedPreferencesUtils.setInt("Message_Count",message_count);
                }
                getActivity().startActivityForResult(intent,300);
                break;
            default:
                break;
        }
    }
    //当用户对单个Item作出各种操作时，都需要调用这个方法进行刷新
    public void settlementSum() {
        totalPrice = 0;
        int sum = 0;
        //判断用户是否全选哦,默认全选
        boolean isCheckall = true;
        for (int i= 0;  i < adapter.getListBeans().size();i++) {
            ShopingCartBean bean = adapter.getListBeans().get(i);
            if (bean.isSelected) {
                double price = Double.parseDouble(bean.goods_price);
                int num = Integer.parseInt(bean.goods_number);
//                sum = sum + num;
                sum = sum + 1;
                totalPrice = totalPrice + price* num;
            }else {
                isCheckall = false;
            }
        }
        if (isCheckall) {
            if (adapter.getListBeans().size() == 0){
                cb_check_all.setChecked(false);
            } else {
                cb_check_all.setChecked(true);
            }
        } else {
            cb_check_all.setChecked(false);
        }
        txt_total_price.setText("RM "+bigDecimal(totalPrice));
        btn_settlement.setText(getResources().getString(R.string.settlement)+"("+sum+")" );
    }
    /**
     * 将小数点后面设为2位数
     * @return
     */
    public String bigDecimal(Double value) {
        if(value != 0.00){
            if (value < 1){
                BigDecimal bg = new BigDecimal(value);
                return bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+"";
            }else  {
                java.text.DecimalFormat df = new java.text.DecimalFormat("########.00");
                return df.format(value);
            }
        }else{
            return "0.00";
        }
    }

    /**
     * 购物车列表接口
     */
    public void cartData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.CART_LIST;
            String user_id = SharedPreferencesUtils.getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }

    /**
     * 修改多个商品数量
     * */
    public void alterNumber() {
        if (lists.size() == 0){
            return;
        }
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (int i = 0; i< lists.size();i++) {
            ShopingCartBean bean = lists.get(i);
            //不相等表示用户已经修改了该商品的数量
            if (!bean.goods_number.equals(bean.initial_number)) {
                Map<String,String> map = new HashMap<String, String>();
                map.put("rec_id",bean.rec_id);
                map.put("goods_number",bean.goods_number);
                list.add(map);
            }
        }
        JSONArray jsonArray = new JSONArray(list);

        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.UPDA_CART;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("rec_ids",jsonArray.toString());
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        }catch (Exception e) {

        }

    }
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray account = json.getJSONArray("cart");
                                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                            lists = Logic.getListToBean(account, new ShopingCartBean());
                            adapter.setLists(lists);
                            adapter.notifyDataSetChanged();
                            //为了判断价格是否变动
                            for (int i = 0; i < lists.size(); i++) {
                                lists.get(i).initial_number = lists.get(i).goods_number;
                            }
                            //当购物车为空时
                            if (lists.size() == 0) {
                                txt_hint.setVisibility(View.VISIBLE);
                                pullToRefreshLayout.setVisibility(View.GONE);
                            } else {
                                txt_hint.setVisibility(View.GONE);
                                pullToRefreshLayout.setVisibility(View.VISIBLE);
                            }
                            settlementSum();
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(getActivity(), getResources().getString(R.string.wdl));
                        }
                    }
                    catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            }
            //修改商品数量
            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            //当修改全部商品数量完成的时候，数量全部初始化
                            for (int i = 0; 0 < lists.size(); i++) {
                                lists.get(i).initial_number = lists.get(i).goods_number;
                            }
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb)
                            );
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw)
                            );
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
            //地址配送
            else if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray account = json.getJSONArray("address");
                            List<AddressBean> lists = Logic.getListToBean(account, new AddressBean());
                            AddressBean bean = lists.get(0);
                            txt_address.setText(bean.address+bean.province+bean.country_2);
                            ll_email.setVisibility(View.VISIBLE);
                            txt_email.setText(bean.city);
                            address_id = bean.address_id;
                            shipping_type = bean.type;
                            shippingData();
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb)
                            );
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw)
                            );
                        } else if (state == 3) {
//                        U.Toast(getActivity(), getResources().getString(R.string.wdl)
//                        );
                        } else if (state == 4) {
                            U.Toast(getActivity(),getResources().getString(R.string.mysj)
                            );
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
            else if (action == 3) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray bd_shipping = json.getJSONArray("shipping");
                            List<BdShippingBean> listbdShipping = Logic.getListToBean(bd_shipping, new BdShippingBean());
                            showBdShippingData(listbdShipping);
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb)
                            );
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw)
                            );
                        }
                    } catch (Exception e) {
                    }
                }
            }
            else if (action == 4) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONObject shipping = json.getJSONObject("feight");
                            JSONArray shippingList = shipping.getJSONArray(shipping_type);
                            List<ShippingBean> listShipping = Logic.getListToBean(shippingList, new ShippingBean());
                            showBdBdShippingData(listShipping);
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb)
                            );
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw)
                            );
                        }
                    } catch (Exception e) {
                    }
                }
            }
            else if (action == 5) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            U.Toast(getActivity(), getResources().getString(R.string.jscg));
                            //删除选中的商品
                            int num = lists.size();
                            for (int i = 0; i < num; i++) {
                                if (adapter.getListBeans().get(i).isSelected) {
                                    adapter.getListBeans().remove(i);
                                    i--;
                                    num--;
                                }
                            }
                            cb_check_all.setChecked(false);
                            totalPrice = 0;
                            txt_total_price.setText("RM " + bigDecimal(totalPrice));
                            btn_settlement.setText(getResources().getString(R.string.settlement) + "(" + 0 + ")");
                            adapter.notifyDataSetChanged();
                            if (!HolidayDialogActivity.getOnes()) {
                                Intent intent = new Intent(getActivity(),HolidayDialogActivity.class);
                                startActivity(intent);
                            }
                            //当购物车为空时
                            if (adapter.getListBeans().size() == 0) {
                                txt_hint.setVisibility(View.VISIBLE);
                                pullToRefreshLayout.setVisibility(View.GONE);
                            } else {
                                txt_hint.setVisibility(View.GONE);
                                pullToRefreshLayout.setVisibility(View.VISIBLE);
                            }
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        } else if (state == 3) {
//                        U.Toast(getActivity(), getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(getActivity(), getResources().getString(R.string.mygwc));
                        }
                    } catch (Exception e) {
                    }
                } else {
                    U.Toast(getActivity(), getResources().getString(R.string.dysb));
                }
                loadingDalog.dismiss();
            }
            //收货人配送
            else if (action == 6) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray account = json.getJSONArray("contact");
                            List<ShippingPersonBean> lists= Logic.getListToBean(account, new ShippingPersonBean());
                            ShippingPersonBean bean = lists.get(0);
                            txt_consignee.setText(bean.consignee);
                            txt_mobile.setText(bean.mobile);
                            contact_id = bean.contact_id;
                        } else if (state == 1) {
                            U.Toast(getActivity(),getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        } else if (state == 3) {
//                        U.Toast(getActivity(), getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(getActivity(), getResources().getString(R.string.mysj));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }


    //==================================================================配送方式==========================================================================================================

    /**
     * 获取地址列表数据
     */
    public void ressListData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.RESS_LIST;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"type"+1,"page"+1,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("type",""+1);
            parmaMap.put("page",""+1);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 2);
        }catch (Exception e) {
        }
    }

    /**
     * 获取收货人列表数据
     */
    public void personListData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.RESS_LIST;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"type"+2,"page"+1,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("type",""+2);
            parmaMap.put("page",""+1);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 6);
        }catch (Exception e) {
        }
    }

    /**
     * 本地运输方式
     */
    public void bdShippingData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.BD_SHIPPING;
        JsonTools.getJsonAll(this, url, parmaMap, 3);
    }

    /**
     * 国际运输方式
     */
    public void shippingData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.SHIPPING;
        JsonTools.getJsonAll(this, url, parmaMap, 4);
    }


    //本地派送选择器
    public void showBdShippingData(final List<BdShippingBean> listbdShipping) {
        List<String > listNameOnes=new ArrayList<String>();
        for (int i = 0; i <listbdShipping.size(); i++) {
            BdShippingBean bean = listbdShipping.get(i);
            String cityname = bean.shipping_name;
            listNameOnes.add(cityname);
        }
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getActivity(),
                R.layout.simple_list_item,
                listNameOnes);
        spr_shipping.setAdapter(adapter1);
        spr_shipping.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                shipping_id = listbdShipping.get(arg2).shipping_id;
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });

    }

    //国际派送选择器
    public void showBdBdShippingData(final List<ShippingBean> listShipping) {
        List<String > listNameOnes=new ArrayList<String>();
        for (int i = 0; i <listShipping.size(); i++) {
            ShippingBean bean = listShipping.get(i);
            String cityname = bean.transport;
            listNameOnes.add(cityname);
        }
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getActivity(),
                R.layout.simple_list_item,
                listNameOnes);
        spr_transport.setAdapter(adapter1);
        spr_transport.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                transport_id = listShipping.get(arg2).transport_id;
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });

    }

    /**
     * 提交
     */
    public void settlementData() {
         if (adapter.getCount()==0) {
            U.Toast(getActivity(), getResources().getString(R.string.shoping_cart_hint));
        }else if (TextUtils.isEmpty(contact_id)) {
            U.Toast(getActivity(), getResources().getString(R.string.add_address_hint_2));
        }else if (TextUtils.isEmpty(address_id)) {
            U.Toast(getActivity(), getResources().getString(R.string.add_address_hint_1));
        } else if (TextUtils.isEmpty(shipping_id)) {
            U.Toast(getActivity(), getResources().getString(R.string.bdpsfsbnwk));
        } else if (TextUtils.isEmpty(transport_id)) {
            U.Toast(getActivity(), getResources().getString(R.string.gjpsfsbnwk));
        } else if (totalPrice == 0) {
            U.Toast(getActivity(), getResources().getString(R.string.spslbnw0));
        }
        else {
            loadingDalog.show();
            try {
                Map<String, String> parmaMap = new HashMap<String, String>();
                String url = Setting.DONE;
                String user_id = getUserBean().user_id;
                Date date = new Date();
                String time = String.valueOf(date.getTime());
                List<Map<String, String>> list = new ArrayList<Map<String, String>>();
                for (int i = 0; i< lists.size();i++) {
                    ShopingCartBean bean = lists.get(i);
                    //选中的商品
                    if (bean.isSelected) {
                        Map<String,String> map = new HashMap<String, String>();
                        map.put("rec_id",bean.rec_id);
                        map.put("memo",bean.remark);
                        list.add(map);
                    }
                }
                JSONArray jsonArray = new JSONArray(list);
                String[] sort = {"user_id" + user_id, "shipping_id" + shipping_id,"address_id"+address_id,"contact_id"+contact_id,"transport"+transport_id, "time" + time};
                String sortStr = Logic.sortToString(sort);
                String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
                parmaMap.put("user_id", user_id);
                parmaMap.put("shipping_id", shipping_id);
                parmaMap.put("address_id", address_id);
                parmaMap.put("contact_id", contact_id);
                parmaMap.put("transport", transport_id);
                parmaMap.put("ids",jsonArray.toString());
                parmaMap.put("time", time);
                parmaMap.put("sign", md5_32);
                parmaMap.put("submit_type","Android");
                JsonTools.getJsonAll(this, url, parmaMap, 5);
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //注销广播
        broadcastManager.unregisterReceiver(myReceiver);
     }
    LocalBroadcastManager broadcastManager;
    /**
     * 注册广播接收器
     */
    private void receiveAdDownload() {
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CommonUtil.SHOPING_CART);
        broadcastManager.registerReceiver(myReceiver, intentFilter);
    }

    /**
     * 通知购物车刷新数据
     */
    private BroadcastReceiver myReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            if(null != lv_shoping_cart){
                cartData();
            }
        }

    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        switch(resultCode){
            case 0:
                if (null !=data) {
                    if (data.hasExtra("AddressBean")) {
                        //当点击地址Item回来的时候
                        AddressBean bean = (AddressBean)data.getSerializableExtra("AddressBean");
                        txt_address.setText(bean.address+bean.province+bean.country_2);
                        address_id = bean.address_id;
                        shipping_type = bean.type;
                        txt_email.setText(bean.city);
                        shippingData();
                    } else if (data.hasExtra("ShippingPersonBean")) {
                        //当点击地址Item回来的时候
                        ShippingPersonBean bean = (ShippingPersonBean)data.getSerializableExtra("ShippingPersonBean");
                        txt_consignee.setText(bean.consignee);
                        txt_mobile.setText(bean.mobile);
                        contact_id = bean.contact_id;
                    }
                }
                break;
        }
    }

    /**
     * 向下刷新
     */
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loadingDalog.show();
        cartData();
    }

    /**
     * 向上加载
     */
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }

}
